/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.
 */
package es.silenus.detecta.util;

import org.apache.commons.mail.HtmlEmail;

import org.springframework.context.MessageSource;

import java.util.Locale;


/**
 * Mail helper class.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 05-abr-2009 13:08:09
 */
public class MailHelper {
	/**
	 * The JNDI address of a mail session.
	 */
	private String jndiMailAddress;

	/**
	 * The encoding.
	 */
	private String encoding;

	/**
	 * The address.
	 */
	private String fromAddress;

	/**
	 * The message source.
	 */
	private MessageSource messageSource;

	/**
	 * Sets the JNDI mail session address.
	 *
	 * @param jndiMailAddress the JNDI mail session address.
	 */
	public void setJndiMailAddress(final String jndiMailAddress) {
		this.jndiMailAddress = jndiMailAddress;
	}

	/**
	 * Sets the encoding.
	 *
	 * @param encoding the encoding.
	 */
	public void setEncoding(final String encoding) {
		this.encoding = encoding;
	}

	/**
	 * Sets the FROM address.
	 *
	 * @param fromAddress the FROM address.
	 */
	public void setFromAddress(final String fromAddress) {
		this.fromAddress = fromAddress;
	}

	/**
	 * Sets the message source.
	 *
	 * @param messageSource the message source.
	 */
	public void setMessageSource(final MessageSource messageSource) {
		this.messageSource = messageSource;
	}

	/**
	 * Sends an HTML email.
	 *
	 * @param toAddress the TO email address.
	 * @param toFullname the TO address sender fullname.
	 * @param locale the locale.
	 * @param subjectKey the subject key.
	 * @param alternateKey the alternate text key.
	 * @param htmlMessage the HTML message.
	 *
	 * @throws Exception if something goes wrong.
	 */
	public void sendHTML(
		final String toAddress, final String toFullname, final Locale locale, final String subjectKey,
		final String alternateKey, final String htmlMessage) throws Exception {
		HtmlEmail email = new HtmlEmail();

		email.setMailSessionFromJNDI(jndiMailAddress);

		email.setCharset(encoding);
		email.setFrom(fromAddress);
		email.setBounceAddress(fromAddress);
		email.addTo(toAddress, toFullname, encoding);

		String subject = messageSource.getMessage(subjectKey, null, locale);
		String alternate = messageSource.getMessage(alternateKey, null, locale);

		email.setSubject(subject);
		email.setHtmlMsg(htmlMessage);
		email.setTextMsg(alternate);

		email.send();
	}
}
